package cn.congine.wizarpos.mall.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.congine.wizarpos.mall.model.ErpCarterOrder;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.ErpProductCategory;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.CateringOrderBindingInput;
import cn.congine.wizarpos.mall.model.open.CateringOrderBindingOutput;
import cn.congine.wizarpos.mall.model.open.CateringOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringOrderQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringReOrderDto;
import cn.congine.wizarpos.mall.model.open.CateringReOrderListQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringReOrderListQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderDto;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderListQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderListQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringStageQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringStageQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringTableOrderStageInput;
import cn.congine.wizarpos.mall.model.open.CateringTableReservedQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringTableReservedQueryOutput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncInput;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncOutput;
import cn.congine.wizarpos.mall.model.open.Table;
import cn.congine.wizarpos.mall.model.open.TableOrder;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.utils.WxSignUtil;
import cn.congine.wizarpos.mall.vo.CateringReOrderView;
import cn.congine.wizarpos.mall.vo.ProductView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "/catering")
public class CateringAction {
	private final Log log = LogFactory.getLog(getClass());

	@Autowired
	private WPosHttpClient wPosHttpClient;

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	 
	@Resource(name = "messageSource")
	private MessageSource messageSource;
	
	/**
	 * 先扫二维码再到menu页  
	 * add xudongdong
	 * @param openId
	 * @param mid
	 * @param httpRequest
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/scan2menu")
	public ModelAndView ys(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		Map<String, Object> data = new HashMap<String, Object>();
		// 商户数据
		MerchantDefQueryInput input = new MerchantDefQueryInput();
		input.setMid(mid);
		MerchantDefQueryOutput output = (MerchantDefQueryOutput) wizarposOpenRestClient.post(input, "/merchantdef/info", MerchantDefQueryOutput.class);		
		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode()) 
				|| StringUtils.isEmpty(output.getResult().getWeixinAppId())
				|| StringUtils.isEmpty(output.getResult().getWeixinAppSecret())) {
			return new ModelAndView("error").addObject("err_message", "商户信息不完整，请完善");
		} 				
		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/scan2menu");
		tmpUrl.append("?openId=").append(openId);
		tmpUrl.append("&mid=").append(mid);
		String url = tmpUrl.toString();		
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appId = result.get("appid");
			//微信 js config 签名
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.put("openId", openId);
			data.put("mid", mid);
			data.putAll(ret);
			data.put("appId", appId);
			data.putAll(ret);
		}
		
		return new ModelAndView("yuding/scan2menu", data);
	}	
	
	/**
	 * 餐饮立即点单（先到menu页下单前在扫码）
	 * @return
	 */
	@RequestMapping("/menuview")
	public ModelAndView menuView() {
		return new ModelAndView("yuding/menu");
	}
	
	/**
	 * 获取可预订的时间段
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/yudingTable", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView getTableStage(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			Model model, HttpServletRequest httpRequest) {
		
		// 请求开放平台 获取 餐厅时段信息
		CateringStageQueryInput input = new CateringStageQueryInput();
		input.setMid(mid);
		CateringStageQueryOutput ouptut = (CateringStageQueryOutput) wizarposOpenRestClient.post(input, "/catering/stage/query", CateringStageQueryOutput.class);
		
//		List<ErpTableOrderStage> list = erpTableOrderStageService.getAll(mid);
		model.addAttribute("stageList", ouptut.getResult());
		model.addAttribute("mid", mid);
		model.addAttribute("openId", openId);
		
		Utils.setSessionToken(httpRequest);
		
		return new ModelAndView("yuding/yuding");
	}

	/**
	 * 根据日期和时段，选择空闲的桌号
	 * 
	 * @param mid
	 * @param date
	 * @param timeStage
	 * @return
	 */
	@RequestMapping(value = "/getUnUsedTables", method = RequestMethod.GET)
	public @ResponseBody List<Table> getUnusedTables(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "selectDate", required = true) String selectDate,
			@RequestParam(value = "selectStageId") String selectStageId,
			@RequestParam(value = "nonceStr") String nonceStr) {
		// 根据日期选择可供预定的桌号
//		com.alibaba.fastjson.JSONArray tables = wPosHttpClient.getUnUsedErpTable(mid, selectDate, selectStageId);
		CateringTableReservedQueryInput input = new CateringTableReservedQueryInput();
		input.setMid(mid);
		input.setDate(selectDate);
		input.setTimeId(selectStageId);
		CateringTableReservedQueryOutput output = (CateringTableReservedQueryOutput) wizarposOpenRestClient.post(input, "/catering/table/unused", CateringTableReservedQueryOutput.class);;
		if (output!= null && output.getResult()!= null) {
			return output.getResult();
		}
		return null;
	}

/*	*//**
	 * 餐桌预订
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws UnsupportedEncodingException
	 *//*
	@RequestMapping(value = "/yudingsubmit")
	public ModelAndView yudingSubmit(
			@RequestParam(value = "date", required = true) String date,
			@RequestParam(value = "time_id", required = true) String time_id,
			@RequestParam(value = "table_id", required = true) String table_id,
			@RequestParam(value = "mans_num", required = true) String mans_num,
			@RequestParam(value = "tel", required = true) String tel,
			@RequestParam(value = "linker", required = true) String linker,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "token", required = true) String token,
			Model model, HttpServletRequest httpRequest,RedirectAttributes attributes)
					throws UnsupportedEncodingException {
		if (Utils.isRepeatSubmit(httpRequest, token)) {
			return new ModelAndView("error").addObject("err_message", "请勿重复提交");
		}
		SimpleDateFormat old = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		
		String nowStr = sf.format(new Date());
	    String oldStr = "1";
		try {
			oldStr = sf.format(old.parse(date));
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		Integer oldInteger = Integer.valueOf(oldStr);
		Integer nowInteger = Integer.valueOf(nowStr);
		
		if(oldInteger - nowInteger < 0) {
			return new ModelAndView("error").addObject("err_message", "请选择今天及今天以后的日期");
		}
		if(oldInteger - nowInteger == 0) {
			ErpTableOrderStage stage = erpTableOrderStageService.getByIdMid(time_id, mid);
			String range = stage.getStageRange();
			Calendar cal = Calendar.getInstance();
			Integer hour = cal.get(Calendar.HOUR_OF_DAY); 
			Integer min = cal.get(Calendar.MINUTE); 
			String timeRange = "";
			if(range.startsWith("-")) {
				timeRange = range.split("-")[1];
			}else if(!range.startsWith("-")&&!range.endsWith("-")) {
				timeRange = range.split("-")[1];
			}
			if(!"".equals(timeRange)) {
				String[] timeArr = timeRange.split(":");
				Integer endHour = Integer.valueOf(timeArr[0]);
				Integer endMin = Integer.valueOf(timeArr[1]);
				if(endHour < hour) {
					return new ModelAndView("error").addObject("err_message", "请选择当前时间以后的时间段");
				}
				if(endHour == hour){
					if(endMin < min){
						return new ModelAndView("error").addObject("err_message", "请选择当前时间以后的时间段");
					}
				}
			}
		}
		
		// 记录创建完删除session中的token
		Utils.removeSessionToken(httpRequest);
		
		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("reOrderDate", date);
		json.put("reOrderName", URLDecoder.decode(linker, "UTF-8"));
		json.put("reOrderNum", mans_num);
		json.put("reOrderPhone", tel);
		json.put("reOrderTimeId", time_id);
		json.put("reAmount", "0");
		JSONArray arr = new JSONArray();
		arr.add(table_id);
		json.put("tableList", arr);

		JSONObject respJson = null;
		try {
			System.out.println("");
			System.out.println("-----/catering/reserve/table----" + time_id);
			System.out.println("");
			respJson = wPosHttpClient.postOpen("/catering/reserve/table", json);
		} catch (Exception e) {
			log.error("请求开放接口，预订餐台失败");
			return new ModelAndView("error").addObject("err_message",
					"请求开放接口，预订餐台失败");
		}

		String code = respJson.getString("code");
		System.out.println("");
		System.out.println("-----code----" + code);
		System.out.println("");
		
		if ("0".equals(code)) {
			String reOrderId = respJson.getJSONObject("result").getString(
					"reOrderId");

			// 记录绑定信息
			WxUserCaterBind obj = new WxUserCaterBind();
			obj.setCarterOrderId(reOrderId);
			obj.setMid(mid);
			obj.setOpenId(openId);
			obj.setCreateTime(new Date());
			caterBindService.save(obj);
			
			model.addAttribute("openId", openId);
			model.addAttribute("mid", mid);
			model.addAttribute("orderId", reOrderId);
			attributes.addFlashAttribute("data",model);
			return new ModelAndView("redirect:/catering/yudingView");
		} else {
			return new ModelAndView("error").addObject("err_message",
					respJson.getString("message"));
		}
	}*/

	/**
	 * 餐桌预订
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/yudingsubmit")
	public ModelAndView yudingSubmit(
			@RequestParam(value = "date", required = true) String date,
			@RequestParam(value = "time_id", required = true) String time_id,
			@RequestParam(value = "table_id", required = true) String table_id,
			@RequestParam(value = "mans_num", required = true) String mans_num,
			@RequestParam(value = "tel", required = true) String tel,
			@RequestParam(value = "linker", required = true) String linker,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "token", required = true) String token,
			Model model, HttpServletRequest httpRequest,RedirectAttributes attributes)
					throws UnsupportedEncodingException {
		
		SimpleDateFormat old = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		
		String nowStr = sf.format(new Date());
	    String oldStr = "1";
		try {
			oldStr = sf.format(old.parse(date));
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		Integer oldInteger = Integer.valueOf(oldStr);
		Integer nowInteger = Integer.valueOf(nowStr);
		
		if(oldInteger - nowInteger < 0) {
			return new ModelAndView("error").addObject("err_message", "请选择今天及今天以后的日期");
		}
		if(oldInteger - nowInteger == 0) {			
			CateringTableOrderStageInput input = new CateringTableOrderStageInput();
			input.setMid(mid);
			input.setId(time_id);
			CommonResultOutput output = (CommonResultOutput) wizarposOpenRestClient.post(input, "/catering/stage/detail", CommonResultOutput.class);						
			String range = ((Map<String, Object>) output.getResult()).get("stageRange").toString();								
			
			Calendar cal = Calendar.getInstance();
			Integer hour = cal.get(Calendar.HOUR_OF_DAY); 
			Integer min = cal.get(Calendar.MINUTE); 
			String timeRange = "";
			if(range.startsWith("-")) {
				timeRange = range.split("-")[1];
			}else if(!range.startsWith("-")&&!range.endsWith("-")) {
				timeRange = range.split("-")[1];
			}
			if(!"".equals(timeRange)) {
				String[] timeArr = timeRange.split(":");
				Integer endHour = Integer.valueOf(timeArr[0]);
				Integer endMin = Integer.valueOf(timeArr[1]);
				if(endHour < hour) {
					return new ModelAndView("error").addObject("err_message", "请选择当前时间以后的时间段");
				}
				if(endHour == hour){
					if(endMin < min){
						return new ModelAndView("error").addObject("err_message", "请选择当前时间以后的时间段");
					}
				}
			}
		}
		
		//判断是否重复提交
		if (Utils.isRepeatSubmit(httpRequest, token)) {
			return new ModelAndView("error").addObject("err_message", "请勿重复提交");
		}
		
		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("reOrderDate", date);
		json.put("reOrderName", URLDecoder.decode(linker, "UTF-8"));
		json.put("reOrderNum", mans_num);
		json.put("reOrderPhone", tel);
		json.put("reOrderTimeId", time_id);
		json.put("reAmount", "0");
		JSONArray arr = new JSONArray();
		arr.add(table_id);
		json.put("tableList", arr);

		JSONObject respJson = null;
		try {
			System.out.println("");
			System.out.println("-----/catering/reserve/table----" + time_id);
			System.out.println("");
			respJson = wPosHttpClient.postOpen("/catering/reserve/table", json);
		} catch (Exception e) {
			log.error("请求开放接口，预订餐台失败");
			return new ModelAndView("error").addObject("err_message",
					"请求开放接口，预订餐台失败");
		}

		String code = respJson.getString("code");
		System.out.println("");
		System.out.println("-----code----" + code);
		System.out.println("");
		
		if ("0".equals(code)) {
			String reOrderId = respJson.getJSONObject("result").getString(
					"reOrderId");

			// 记录绑定信息
			CateringOrderBindingInput input = new CateringOrderBindingInput();
			input.setMid(mid);
			input.setOpenId(openId);
			input.setOrderId(reOrderId);
			CateringOrderBindingOutput ouptut = (CateringOrderBindingOutput) wizarposOpenRestClient.post(input, "/catering/order/binding", CateringOrderBindingOutput.class);
			
			model.addAttribute("openId", openId);
			model.addAttribute("mid", mid);
			model.addAttribute("orderId", reOrderId);
			attributes.addFlashAttribute("data",model);
			return new ModelAndView("redirect:/catering/yudingView");
		} else {
			return new ModelAndView("error").addObject("err_message",
					respJson.getString("message"));
		}
	}
	
	@RequestMapping("/yudingView")
	public ModelAndView yudingView()
	{
		return new ModelAndView("yuding/yudingok");
	}

/*	*//**
	 * 餐桌预订详情
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws Exception 
	 *//*
	@RequestMapping(value = "/yudinginfo")
	public ModelAndView yudingInfo(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest,Model model) throws Exception {
		
		ErpCarterOrder erpCarterOrder = erpCarterOrderService.getByIdMid(
				orderId, mid);
		// 截取显示单号
		erpCarterOrder.setShowOrderId(Function.getShowWxOrderNo(erpCarterOrder.getOrderId()));
		// 转换显示金额
		erpCarterOrder.setOrderAmount(Utils.formatAmount(erpCarterOrder
				.getOrderAmount()));
		// 转换显示时段
		ErpTableOrderStage stage = erpTableOrderStageService.getByIdMid(
				erpCarterOrder.getStageId(), mid);
		erpCarterOrder.setStageId(stage.getStageRange());
		// 转换显示餐桌
		ErpTable table = tableDefService.getTable(mid,
				erpCarterOrder.getTableId());
		if (table.getTableName() != null) {
			erpCarterOrder.setShowTable(table.getTableName());
		} else {
			erpCarterOrder.setShowTable(table.getTableNo());
		}

		model.addAttribute("order", erpCarterOrder);
		model.addAttribute("openId", openId);
		model.addAttribute("mid", mid);
		
		return new ModelAndView("yuding/yudinginfo");
	}*/
	
	/**
	 * 餐桌预订详情
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/yudinginfo")
	public ModelAndView yudingInfo(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest,Model model) throws Exception {
		CateringOrderQueryInput cateringOrderQueryInput = new CateringOrderQueryInput();
		cateringOrderQueryInput.setMid(mid);
		cateringOrderQueryInput.setReOrderId(orderId);
		CateringOrderQueryOutput cateringOrderQueryOutput = (CateringOrderQueryOutput) wizarposOpenRestClient.post(cateringOrderQueryInput, "/catering/reorder/query", CateringOrderQueryOutput.class);
		List<TableOrder> tableOrderList = cateringOrderQueryOutput.getResult();
		TableOrder tableOrder = tableOrderList.get(0);
		ErpCarterOrder erpCarterOrder = new ErpCarterOrder();	
		// 截取显示单号
		erpCarterOrder.setShowOrderId(Function.getShowWxOrderNo(tableOrder.getOrderId()));
		// 转换显示金额
		erpCarterOrder.setOrderAmount(Utils.formatAmount(tableOrder.getReAmount()));
		// 转换显示时段
		erpCarterOrder.setStageId(tableOrder.getReOrderTimeRange());
		// 转换显示餐桌
		List<Table> tableList = tableOrder.getTableList();		
		Table table = tableList.get(0);	
		erpCarterOrder.setShowCreateTime(tableOrder.getCreateTime());
		erpCarterOrder.setOrderDate(tableOrder.getReOrderDate());
		erpCarterOrder.setAuditFlag(Integer.parseInt(tableOrder.getAuditFlag()));
		erpCarterOrder.setOrderMansNum(tableOrder.getOrderMansNum());
		erpCarterOrder.setOrderTel(tableOrder.getReOrderPhone());
		erpCarterOrder.setOrderLinker(tableOrder.getReOrderName());
		erpCarterOrder.setTableId(table.getTableId());		
		if (table != null && table.getTableName() != null) {
			erpCarterOrder.setShowTable(table.getTableName());
		} else {
			erpCarterOrder.setShowTable(table.getTableCode());
		}		

		model.addAttribute("order", erpCarterOrder);
		model.addAttribute("openId", openId);
		model.addAttribute("mid", mid);
		
		return new ModelAndView("yuding/yudinginfo");
	}	

	/**
	 * 呼叫服务，通知商家，1呼叫加水，2呼叫买单，3提醒已经点单
	 * 
	 * @param table_id
	 * @param openId
	 * @param mid
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/callwaiter")
	public @ResponseBody String callWaiter(
			@RequestParam(value = "flag", required = true) String flag,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid)
			throws UnsupportedEncodingException {
		// 校验餐桌是否是开桌状态
		Boolean isUsing = wPosHttpClient.isTableUsing(mid, tableId);
		if (!isUsing) {
			return "2";
		}
		
		// pos消息提醒推送
		StringBuffer msg = new StringBuffer();
		if ("1".equals(flag)) {
			msg.append("需要加水");
		} else if ("2".equals(flag)) {
			msg.append("需要买单");
		} else if ("3".equals(flag)) {
			msg.append("已经点餐");
		}
		JSONObject param = new JSONObject();
		param.put("mid", mid);
		param.put("sendMessage", msg);
		param.put("tableId", tableId);
		try {
			wPosHttpClient.postOpen("/catering/service/call", param);
		} catch (Exception e) {
			// 消息推送失败
			log.error("推送呼叫服务消息失败，餐桌ID = " + tableId);
			log.error(e);
			return "1";
		}

		return "0";
	}

/*	*//**
	 * 
	 * @param token
	 * @param tableId
	 * @param openId
	 * @param mid
	 * @param orderNum
	 * @param sum
	 * @param orderDetail
	 * @param reOrderId 预订单id
	 * @param httpRequest
	 * @param attributes
	 * @return
	 * @throws UnsupportedEncodingException
	 *//*
	@RequestMapping(value = "/submitmenu")
	public ModelAndView submitMenu(
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			HttpServletRequest httpRequest,RedirectAttributes attributes) throws UnsupportedEncodingException {

		System.out.println("");
		System.out.println("-----/submitmenu----enter");
		System.out.println("");
		
		if (Utils.isRepeatSubmit(httpRequest, token)) {
			return new ModelAndView("error").addObject("err_message", "请勿重复提交");
		}
		
		if (reOrderId == null || reOrderId.isEmpty()) {// TODO 是否查看有无预订单
//			Object stageId = erpTableOrderStageService.getCurrentStage(mid);
//			if (stageId != null) {
//				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//				Date today = null;
//				try {
//					today = format.parse(format.format(new Date()));
//				} catch (ParseException e) {
//					e.printStackTrace();
//				}
//				reOrderId = (String)erpCarterOrderService.getReOrderId(mid, today,
//						stageId.toString(), tableId);
//			}
		} else {
			ErpCarterOrder erpCarterOrder = erpCarterOrderService.getByIdMid(
					reOrderId, mid);
			if(erpCarterOrder != null && erpCarterOrder.getAuditFlag() != 1 && !"0".equals(erpCarterOrder.getStatus())) {
			//接受了的预订单，且未开桌的预定才可以在线点单
				return new ModelAndView("error").addObject("err_message",
						"预定已经失效");
			}
		}

		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("orderId", null);
		json.put("reOrderId", reOrderId);
		JSONArray arr = new JSONArray();
		arr.add(tableId);
		json.put("tableId", arr);
		json.put("orderType", "1");//堂吃
		json.put("orderSource", "2");//微信订单
		json.put("status", "0");
		json.put("amount", sum);
		json.put("orderNum", orderNum);
		json.put("orderDetail", JSON.parseArray(orderDetail));
		json.put("print", true);
		
		JSONObject respJson = null;
		try {
			respJson = wPosHttpClient.postOpen("/catering/saleorder/submit",
					json);
		} catch (Exception e) {
			System.out.println("");
			System.out.println("-----/submitmenu----" + e.getMessage());
			System.out.println("");
			// 消息推送失败
			log.error("点餐失败，桌号："
					+ tableDefService.getTable(mid, tableId).getTableNo());
			return new ModelAndView("error").addObject("err_message",
					"系统错误，点餐失败。");
		}

		String code = respJson.getString("code");
		if ("0".equals(code) || "60032".equals(code)) {
			System.out.println("");
			System.out.println("-----/submitmenu--success--code:"+code);
			System.out.println("");
			String orderId = respJson.getJSONObject("result").getString(
					"orderId");

			// 记录绑定信息
			WxUserCaterSaleBind obj = new WxUserCaterSaleBind();
			obj.setCarterSaleOrderId(orderId);
			obj.setMid(mid);
			obj.setOpenId(openId);
			obj.setCreateTime(new Date());
			caterSaleBindService.save(obj);

			System.out.println("");
			System.out.println("-----/submitmenu----token:" + token);
			System.out.println("");
			System.out.println("");
			System.out.println("-----/submitmenu----session:" + httpRequest.getSession().getAttribute(
					SysConstants.SESSION_TOKEN));
			System.out.println("");
			// 记录创建完删除session中的token
			Utils.removeSessionToken(httpRequest);
			
			attributes.addFlashAttribute("data",obj);
			return new ModelAndView("redirect:/catering/menuOkView");
			return new ModelAndView("yuding/menuok").addObject("mid", mid)
					.addObject("openId", openId).addObject("orderId", orderId);
		} else {
			System.out.println("");
			System.out.println("-----/submitmenu--fail--code:" + code);
			System.out.println("");
			if ("60025".equals(code)) {
				return new ModelAndView("error").addObject("err_message",
						"桌子不可用，请找服务员点单");
			}
			if ("60035".equals(code)) {
				return new ModelAndView("error").addObject("err_message",
						"桌子已经开台，请在找服务员点单");
			}
			return new ModelAndView("error").addObject("err_message",
					respJson.getString("message"));
		}
	}*/
	
/*	*//**
	 * 
	 * @param token
	 * @param tableId
	 * @param openId
	 * @param mid
	 * @param orderNum
	 * @param sum
	 * @param orderDetail
	 * @param reOrderId 预订单id
	 * @param httpRequest
	 * @param attributes
	 * @return
	 * @throws UnsupportedEncodingException
	 *//*
	@RequestMapping(value = "/submitmenu")
	public ModelAndView submitMenu(
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			HttpServletRequest httpRequest,RedirectAttributes attributes) throws UnsupportedEncodingException {

		System.out.println("");
		System.out.println("-----/submitmenu----enter");
		System.out.println("");
		
		if (reOrderId == null || reOrderId.isEmpty()) {// TODO 是否查看有无预订单
//			Object stageId = erpTableOrderStageService.getCurrentStage(mid);
//			if (stageId != null) {
//				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//				Date today = null;
//				try {
//					today = format.parse(format.format(new Date()));
//				} catch (ParseException e) {
//					e.printStackTrace();
//				}
//				reOrderId = (String)erpCarterOrderService.getReOrderId(mid, today,
//						stageId.toString(), tableId);
//			}
		} else {
			ErpCarterOrder erpCarterOrder = erpCarterOrderService.getByIdMid(
					reOrderId, mid);
			if(erpCarterOrder != null && erpCarterOrder.getAuditFlag() != 1 && !"0".equals(erpCarterOrder.getStatus())) {
			//接受了的预订单，且未开桌的预定才可以在线点单
				return new ModelAndView("error").addObject("err_message",
						"预定已经失效");
			}
		}

		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("orderId", null);
		json.put("reOrderId", reOrderId);
		JSONArray arr = new JSONArray();
		arr.add(tableId);
		json.put("tableId", arr);
		json.put("orderType", "1");//堂吃
		json.put("orderSource", "2");//微信订单
		json.put("status", "0");
		json.put("amount", sum);
		json.put("orderNum", orderNum);
		json.put("orderDetail", JSON.parseArray(orderDetail));
		json.put("print", true);
		
		JSONObject respJson = null;
		try {
			respJson = wPosHttpClient.postOpen("/catering/saleorder/submit",
					json);
		} catch (Exception e) {
			System.out.println("");
			System.out.println("-----/submitmenu----" + e.getMessage());
			System.out.println("");
			// 消息推送失败
			log.error("点餐失败，桌号："
					+ tableDefService.getTable(mid, tableId).getTableNo());
			return new ModelAndView("error").addObject("err_message",
					"系统错误，点餐失败。");
		}

		String code = respJson.getString("code");
		if ("0".equals(code) || "60032".equals(code)) {
			System.out.println("");
			System.out.println("-----/submitmenu--success--code:"+code);
			System.out.println("");
			String orderId = respJson.getJSONObject("result").getString(
					"orderId");

			// 记录绑定信息			
			CateringSaleOrderBindingInput input = new CateringSaleOrderBindingInput();
			input.setMid(mid);
			input.setOpenId(openId);
			input.setSaleOrderId(orderId);
			CateringSaleOrderBindingOutput ouptut = (CateringSaleOrderBindingOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/binding", CateringSaleOrderBindingOutput.class);			
		
			WxUserCaterSaleBind obj = new WxUserCaterSaleBind();
			obj.setCarterSaleOrderId(orderId);
			obj.setMid(mid);
			obj.setOpenId(openId);

			System.out.println("");
			System.out.println("-----/submitmenu----token:" + token);
			System.out.println("");
			System.out.println("");
			System.out.println("-----/submitmenu----session:" + httpRequest.getSession().getAttribute(
					SysConstants.SESSION_TOKEN));
			System.out.println("");
			if (Utils.isRepeatSubmit(httpRequest, token)) {
				return new ModelAndView("error").addObject("err_message", "请勿重复提交");
			}
			
			attributes.addFlashAttribute("data",obj);
			return new ModelAndView("redirect:/catering/menuOkView");
			return new ModelAndView("yuding/menuok").addObject("mid", mid)
					.addObject("openId", openId).addObject("orderId", orderId);
		} else {
			System.out.println("");
			System.out.println("-----/submitmenu--fail--code:" + code);
			System.out.println("");
			if ("60025".equals(code)) {
				return new ModelAndView("error").addObject("err_message",
						"桌子不可用，请找服务员点单");
			}
			if ("60035".equals(code)) {
				return new ModelAndView("error").addObject("err_message",
						"桌子已经开台，请在找服务员点单");
			}
			return new ModelAndView("error").addObject("err_message",
					respJson.getString("message"));
		}
	}	*/

	/**
	 * 
	 * @param token
	 * @param tableId
	 * @param openId
	 * @param mid
	 * @param orderNum
	 * @param sum
	 * @param orderDetail
	 * @param reOrderId 预订单id
	 * @param httpRequest
	 * @param attributes
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/submitmenu")
	public ModelAndView submitMenu(
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			@RequestParam(value = "remark", required = false) String remark,//add xudongdong
			HttpServletRequest httpRequest,RedirectAttributes attributes) throws UnsupportedEncodingException {

		System.out.println("");
		System.out.println("-----/submitmenu----enter");
		System.out.println("");
		
		if (reOrderId == null || reOrderId.isEmpty()) {// TODO 是否查看有无预订单
//			Object stageId = erpTableOrderStageService.getCurrentStage(mid);
//			if (stageId != null) {
//				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//				Date today = null;
//				try {
//					today = format.parse(format.format(new Date()));
//				} catch (ParseException e) {
//					e.printStackTrace();
//				}
//				reOrderId = (String)erpCarterOrderService.getReOrderId(mid, today,
//						stageId.toString(), tableId);
//			}
		} else {
			CateringOrderQueryInput input = new CateringOrderQueryInput();
			input.setMid(mid);
			input.setReOrderId(reOrderId);
			CateringOrderQueryOutput ouptut = (CateringOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/reorder/query", CateringOrderQueryOutput.class);							
			List<TableOrder> tableOrderList = ouptut.getResult();		
			if (tableOrderList.size() != 0 && !"1".equals(tableOrderList.get(0).getAuditFlag()) 
					&& !"0".equals(tableOrderList.get(0).getStatus())) {		
				//接受了的预订单，且未开桌的预定才可以在线点单
				return new ModelAndView("error").addObject("err_message",
						"预定已经失效");
			}
		}

		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("orderId", null);
		json.put("reOrderId", reOrderId);
		JSONArray arr = new JSONArray();
		arr.add(tableId);
		json.put("tableId", arr);
		json.put("orderType", "1");//堂吃
		json.put("orderSource", "2");//微信订单
		json.put("status", "0");
		json.put("amount", sum);
		json.put("orderNum", orderNum);
		json.put("orderDetail", JSON.parseArray(orderDetail));
		json.put("print", true);		
		json.put("remark", URLDecoder.decode(remark, "UTF-8"));
		
		JSONObject respJson = null;
		try {
			respJson = wPosHttpClient.postOpen("/catering/saleorder/submit",
					json);
		} catch (Exception e) {
			System.out.println("");
			System.out.println("-----/submitmenu----" + e.getMessage());
			System.out.println("");
			// 消息推送失败
			log.error("点餐失败，餐桌ID = " + tableId);
			return new ModelAndView("error").addObject("err_message",
					"系统错误，点餐失败。");
		}

		String code = respJson.getString("code");
		if ("0".equals(code) || "60032".equals(code)) {
			System.out.println("");
			System.out.println("-----/submitmenu--success--code:"+code);
			System.out.println("");
			String orderId = respJson.getJSONObject("result").getString(
					"orderId");

			// 记录绑定信息			
			CateringSaleOrderBindingInput input = new CateringSaleOrderBindingInput();
			input.setMid(mid);
			input.setOpenId(openId);
			input.setSaleOrderId(orderId);
			CateringSaleOrderBindingOutput ouptut = (CateringSaleOrderBindingOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/binding", CateringSaleOrderBindingOutput.class);			

			System.out.println("");
			System.out.println("-----/submitmenu----token:" + token);
			System.out.println("");
			System.out.println("");
			System.out.println("-----/submitmenu----session:" + httpRequest.getSession().getAttribute(
					SysConstants.SESSION_TOKEN));
			System.out.println("");
			if (Utils.isRepeatSubmit(httpRequest, token)) {
				return new ModelAndView("error").addObject("err_message", "请勿重复提交");
			}
			
			attributes.addFlashAttribute("mid",mid);
			attributes.addFlashAttribute("openId",openId);
			attributes.addFlashAttribute("carterSaleOrderId",orderId);
			return new ModelAndView("redirect:/catering/menuOkView");
/*			return new ModelAndView("yuding/menuok").addObject("mid", mid)
					.addObject("openId", openId).addObject("orderId", orderId);*/
		} else {
			System.out.println("");
			System.out.println("-----/submitmenu--fail--code:" + code);
			System.out.println("");
			if ("60025".equals(code)) {
				return new ModelAndView("error").addObject("err_message",
						"桌子不可用，请找服务员点单");
			}
			if ("60035".equals(code)) {
				return new ModelAndView("error").addObject("err_message",
						"桌子已经开台，请在找服务员点单");
			}
			return new ModelAndView("error").addObject("err_message",
					respJson.getString("message"));
		}
	}	
	
	@RequestMapping("/menuOkView")
	public ModelAndView menuOkView()
	{
		return new ModelAndView("yuding/menuok");
	}

/*	*//**
	 * 点单明细
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 *//*
	@RequestMapping(value = "/menudetail")
	public ModelAndView menuDetail(
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			Model model, HttpServletRequest httpRequest)
			throws UnsupportedEncodingException {

		com.alibaba.fastjson.JSONArray detailArray = JSON
				.parseArray(orderDetail);
		List<ProductView> list = new ArrayList<ProductView>();
		for (int i = 0; i < detailArray.size(); i++) {
			JSONObject detail = detailArray.getJSONObject(i);
			ProductView pv = new ProductView();
			pv.setId(detail.getString("id"));
			pv.setName(URLDecoder.decode(detail.getString("name"), "UTF-8"));
			pv.setPrice(detail.getString("price"));
			pv.setNum(detail.getInteger("qty"));
			pv.setCode(detail.getString("code"));
			list.add(pv);
		}

		model.addAttribute("products", list);
		model.addAttribute("sum", sum);
		model.addAttribute("tableId", tableId);
		model.addAttribute("orderNum", orderNum);
		model.addAttribute("order", "");
		model.addAttribute("openId", openId);
		model.addAttribute("mid", mid);
		model.addAttribute("reOrderId", reOrderId);
		Utils.setSessionToken(httpRequest);

		return new ModelAndView("yuding/menudetail");
	}*/
	
	/**
	 * 点单明细
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/menudetail")
	public ModelAndView menuDetail(
			@RequestParam(value = "tableId", required = false) String tableId,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			Model model, HttpServletRequest httpRequest, RedirectAttributes attributes)
			throws IOException {

		com.alibaba.fastjson.JSONArray detailArray = JSON
				.parseArray(orderDetail);
		List<ProductView> list = new ArrayList<ProductView>();
		for (int i = 0; i < detailArray.size(); i++) {
			JSONObject detail = detailArray.getJSONObject(i);
			ProductView pv = new ProductView();
			pv.setId(detail.getString("id"));
			pv.setName(URLDecoder.decode(detail.getString("name"), "UTF-8"));
			pv.setPrice(detail.getString("price"));
			pv.setNum(detail.getInteger("qty"));
			pv.setCode(detail.getString("code"));
			list.add(pv);
		}
		// 商户数据
		MerchantDefQueryInput input = new MerchantDefQueryInput();
		input.setMid(mid);
		MerchantDefQueryOutput output = (MerchantDefQueryOutput) wizarposOpenRestClient.post(input, "/merchantdef/info", MerchantDefQueryOutput.class);		
		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode()) 
				|| StringUtils.isEmpty(output.getResult().getWeixinAppId())
				|| StringUtils.isEmpty(output.getResult().getWeixinAppSecret())) {
			return new ModelAndView("error").addObject("err_message", "商户信息不完整，请完善");
		}		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/menudetailview");
		String url = tmpUrl.toString();		
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appId = result.get("appid");
			//微信 js config 签名
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			attributes.addFlashAttribute("timestamp",ret.get("timestamp"));
			attributes.addFlashAttribute("noncestr",ret.get("noncestr"));
			attributes.addFlashAttribute("signature",ret.get("signature"));
			attributes.addFlashAttribute("appId", appId);
		}
		attributes.addFlashAttribute("products", list);
		attributes.addFlashAttribute("sum", sum);
		attributes.addFlashAttribute("tableId", tableId);
		attributes.addFlashAttribute("orderNum", orderNum);
		attributes.addFlashAttribute("order", "");
		attributes.addFlashAttribute("openId", openId);
		attributes.addFlashAttribute("mid", mid);
		attributes.addFlashAttribute("reOrderId", reOrderId);		
		Utils.setSessionToken(httpRequest);
		return new ModelAndView("redirect:/catering/menudetailview");
	}

	@RequestMapping("/menudetailview")
	public ModelAndView menuDetailView() {
		return new ModelAndView("yuding/menudetail");
	}
	
	/**
	 * 点单详情
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/menuinfo")
	public ModelAndView menuInfo(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid)
			throws UnsupportedEncodingException {
		JSONObject param = new JSONObject();
		param.put("mid", mid);
		param.put("orderId", orderId);
		JSONObject orderJson = null;
		try {
			orderJson = wPosHttpClient.postOpen("/catering/saleorder/query",
					param);
		} catch (Exception e) {
			// 消息推送失败
			log.error("餐饮订单查询失败，单号：" + orderId);
			return new ModelAndView("error").addObject("err_message", "系统错误。");
		}
		
		if ("0".equals(orderJson.getString("code"))) {
			JSONObject cardJson = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
			String cardId = null;
			com.alibaba.fastjson.JSONArray tickets = null;
			if (cardJson.getIntValue("code") == 0) {
				JSONObject cardVip = cardJson.getJSONObject("result");
				// 获取对应的会员卡卡号
				cardId = cardVip.getString("id");
				if (cardId != null) {
					JSONObject ticketJson = wPosHttpClient.getCashTickets(openId, mid);
					if (ticketJson.getIntValue("code") == 0) {
						tickets = ticketJson.getJSONArray("result");//代金券
						for (int i = 0; i < tickets.size(); i++) {
							JSONObject obj = tickets.getJSONObject(i);
							obj.put("balance", Utils.formatAmount(obj.getString("balance")));			
						}
					}
				}
			}
			//若未填写订单备注，则页面显示无
			if (StringUtils.isEmpty(orderJson.getJSONObject("result").getString("remark"))) {
				orderJson.getJSONObject("result").put("remark", "无");
			}
			
			return new ModelAndView("yuding/menuinfo").addObject("mid", mid)
					.addObject("openId", openId)
					.addObject("orderId", orderId)
					.addObject("order", orderJson.getJSONObject("result"))
					.addObject("cashList", tickets)
					.addObject("cardId", cardId);
		} else {
			return new ModelAndView("error").addObject("err_message",
					orderJson.getString("message"));
		}
	}

	
	/**
	 * 去支付
	 * 
	 * @param orderId
	 * @param openId
	 * @param mid
	 * @param payType
	 * 			0 微信支付  1会员卡支付
	 * @param ticketId
	 * 			代金券
	 * @return
	 */
	@RequestMapping(value = "/topay", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView topay(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "payType", required = false) String payType,
			@RequestParam(value = "ticketInfoIds", required = false) String ticketInfoIds,
			RedirectAttributes attributes) {
		
		JSONObject param = new JSONObject();
		param.put("mid", mid);
		param.put("orderId", orderId);
		param.put("amount", sum);
		param.put("ticketInfoIds", JSON.parseArray(ticketInfoIds));
		param.put("print", true);
		
		JSONObject json = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
		int code = json.getIntValue("code");
		int balance = 0;
		if (code == 0) {
			JSONObject cardVip = json.getJSONObject("result");
			// 获取对应的会员卡卡号
			String cardNo = cardVip.getString("cardNo");
			balance= cardVip.getIntValue("balance");
			param.put("cardNo", cardNo);
		}
		
		if ("1".equals(payType) && balance < Double.valueOf(sum)*100) {
			return new ModelAndView("error").addObject("err_message", "会员卡余额不足。");
		}
		
		JSONObject orderJson = null;
		try {
			orderJson = wPosHttpClient.postOpen("/catering/memberCardPay",
					param);
		} catch (Exception e) {
			// 消息推送失败
			log.error("餐饮订单支付失败，单号：" + orderId);
			return new ModelAndView("error").addObject("err_message", "系统错误。");
		}
		
		if ("0".equals(orderJson.getString("code"))) {
			
			attributes.addFlashAttribute("mid", mid);
			attributes.addFlashAttribute("openId", openId);
			attributes.addFlashAttribute("orderId", orderId);
			
			return new ModelAndView("redirect:/catering/okView");
//			return new ModelAndView("takeout/orderok")
//			.addObject("mid", mid)
//			.addObject("openId", openId).addObject("orderId", orderId);
		} else {
			return new ModelAndView("error").addObject("err_message", orderJson.getString("message"));
		}
	}

	@RequestMapping("/okView")
	public ModelAndView okView()
	{
		//return new ModelAndView("takeout/orderok");
		return new ModelAndView("yuding/payok");
	}
	
/*	*//**
	 * 进入点餐
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 *//*
	@RequestMapping(value = "/tomenu", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toMenu(
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "reOrderId", required = false) String reOrderId) {
		Map<String, Object> data = new HashMap<String, Object>();
		List<ErpProductCategory> categoryList = erpProductCategoryService
				.getErpProductCategory(mid);
		Map<String, Object> products = new HashMap<String, Object>();
		for (ErpProductCategory category : categoryList) {
			String categoryId = category.getId();
			String categoryCode = category.getCode();
			List<ErpProduct> productList = erpProductService
					.getErpProductListByPage(mid, categoryId, 1);
			// 处理价格分-元，图片路径
			for (ErpProduct ep : productList) {
				ep.setPrice(Utils.formatAmount(ep.getPrice()));
				ep.setShowMemPrice(Utils.formatAmount(ep.getMemberPrice()));
				ep.setPicUrl(getPrituce(ep.getId()));
			}
			// 迭代此分类下所有产品
			// getproductsUnderCategory(mid, categoryId, productList);

			products.put("topten" + categoryCode, productList);
		}
		
		JSONObject json = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
		int code = json.getIntValue("code");
		if (code == 0) {
			JSONObject cardVip = json.getJSONObject("result");
			// 获取对应的会员卡卡号
			String cardId = cardVip.getString("id");
			data.put("cardId", cardId);
		}
		data.put("products", products);
		data.put("categoryList", categoryList);
		data.put("mid", mid);
		data.put("openId", openId);
		data.put("tableId", tableId);
		data.put("reOrderId", reOrderId);
		return new ModelAndView("yuding/menu", data);
	}*/

	/**
	 * 进入点餐
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/tomenu", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toMenu(
			@RequestParam(value = "tableId", required = false) String tableId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			RedirectAttributes attributes) {								
		Map<String, Object> data = new HashMap<String, Object>();
		
		ProductCategorySyncInput productCategorySyncInput = new ProductCategorySyncInput();
		productCategorySyncInput.setMid(mid);		
		ProductCategorySyncOutput productCategorySyncOutput = (ProductCategorySyncOutput) wizarposOpenRestClient.post(productCategorySyncInput, "/product/category", ProductCategorySyncOutput.class);
		
		List<ErpProductCategory>  categoryList = productCategorySyncOutput.getResult();	
		
		Map<String, Object> products = new HashMap<String, Object>();
		for (ErpProductCategory category : categoryList) {
			String categoryId = category.getId();
			String categoryCode = category.getCode();
			
			MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
			merchandiseSyncInput.setMid(mid);
			merchandiseSyncInput.setCategoryId(categoryId);
			merchandiseSyncInput.setPageNo("1");
			MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(merchandiseSyncInput, "/product/merchandise", MerchandiseSyncOutput.class);					
			
			List<Merchandise>  productListTemp = merchandiseSyncOutput.getResult();
			List<ErpProduct> productList = new ArrayList<ErpProduct>();			
			// 处理价格分-元，图片路径
			for (Merchandise prt : productListTemp) {
				ErpProduct ep = new ErpProduct();				
				ep.setId(prt.getProductId());
				ep.setCode(prt.getCode());
				ep.setName(prt.getName());				
				ep.setPrice(prt.getPrice());				
				ep.setShowMemPrice(prt.getMemberPrice());
				if ("".equals(prt.getPicUrl())) {
					ep.setPicUrl(SysConstants.DEFAULT_PICTURE);
				} else {
					ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl(), 150, 150));
				}
				productList.add(ep);
			}		
			// 迭代此分类下所有产品
			// getproductsUnderCategory(mid, categoryId, productList);

			products.put("topten" + categoryCode, productList);
		}
		
		JSONObject json = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
		int code = json.getIntValue("code");
		if (code == 0) {
			JSONObject cardVip = json.getJSONObject("result");
			// 获取对应的会员卡卡号
			String cardId = cardVip.getString("id");
			//data.put("cardId", cardId);
			attributes.addFlashAttribute("cardId", cardId);
		}
//		data.put("products", products);
//		data.put("categoryList", categoryList);
//		data.put("mid", mid);
//		data.put("openId", openId);
//		data.put("tableId", tableId);
//		data.put("reOrderId", reOrderId);
//		return new ModelAndView("yuding/menu", data);
		
		attributes.addFlashAttribute("products", products);
		attributes.addFlashAttribute("categoryList", categoryList);
		attributes.addFlashAttribute("mid", mid);
		attributes.addFlashAttribute("openId", openId);
		attributes.addFlashAttribute("tableId", tableId);
		attributes.addFlashAttribute("reOrderId", reOrderId);
		
		return new ModelAndView("redirect:/catering/menuview");
	}
	
/*	*//**
	 * 下一页菜品
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 *//*
	@RequestMapping(value = "/moreProduct", method = RequestMethod.GET)
	public @ResponseBody List<ErpProduct> moreProduct(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "category", required = true) String category,
			@RequestParam(value = "pageIndex", required = true) int pageIndex) {
		String categoryCode = category.substring(6);
		ErpProductCategory cate = erpProductCategoryService.getErpProductCategoryByCode(mid, categoryCode);
		List<ErpProduct> productList = null;
		if (cate != null) {
			productList = erpProductService
					.getErpProductListByPage(mid, cate.getId(), pageIndex);
			// 处理价格分-元，图片路径
			for (ErpProduct ep : productList) {
				ep.setPrice(Utils.formatAmount(ep.getPrice()));
				ep.setPicUrl(getPrituce(ep.getId()));
			}
			// 迭代此分类下所有产品
			// getproductsUnderCategory(mid, categoryId, productList);
		}
		return productList; 
	}*/
	
	/**
	 * 下一页菜品
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/moreProduct", method = RequestMethod.GET)
	public @ResponseBody List<ErpProduct> moreProduct(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "category", required = true) String category,
			@RequestParam(value = "pageIndex", required = true) int pageIndex) {	
		String categoryCode = category.substring(6);		
		MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
		merchandiseSyncInput.setMid(mid);
		merchandiseSyncInput.setCategoryCode(categoryCode);		
		merchandiseSyncInput.setPageNo(Integer.toString(pageIndex));
		MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(merchandiseSyncInput, "/product/merchandise", MerchandiseSyncOutput.class);					
		
		List<Merchandise>  productListTemp = merchandiseSyncOutput.getResult();		
		if (productListTemp == null) {
			return null;
		}
		List<ErpProduct> productList = new ArrayList<ErpProduct>();			
		// 处理价格分-元，图片路径
		for (Merchandise prt : productListTemp) {
			ErpProduct ep = new ErpProduct();				
			ep.setId(prt.getProductId());
			ep.setCode(prt.getCode());
			ep.setName(prt.getName());				
			ep.setPrice(prt.getPrice());				
			ep.setShowMemPrice(prt.getMemberPrice());
			if ("".equals(prt.getPicUrl())) {
				ep.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl(), 150, 150));
			}
			productList.add(ep);
		}			
		return productList; 
	}	

/*	*//**
	 * 进入餐点订单列表
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 *//*
	@RequestMapping(value = "/myorders", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView myOrder(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid) {

		List<Object[]> caterOrderList = caterBindService.getByOpenIdMid(openId,
				mid);
		List<Object[]> caterSaleOrderList = caterSaleBindService
				.getByOpenIdMid(openId, mid);

		List<CateringReOrderView> orderList = new ArrayList<CateringReOrderView>();
		List<CateringReOrderView> endedList = new ArrayList<CateringReOrderView>();

		for (Object[] obj : caterOrderList) {
			CateringReOrderView reOrderView = new CateringReOrderView();
			reOrderView.setOrderId(obj[9].toString());
			reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj[0].toString()));
			reOrderView.setTable(obj[1].toString());
			reOrderView.setStageRange(obj[3].toString());
			reOrderView.setCreateTime(obj[4].toString());
			reOrderView.setAmount(Utils.formatAmount(obj[5].toString()));
			reOrderView.setOrderDate(obj[8].toString());
			reOrderView.setType("1");
			if (obj[7] == null || "0".equals(obj[7].toString())) {// 待接受
				reOrderView.setStatus("0");
				orderList.add(reOrderView);
			} else if ("2".equals(obj[7].toString())) {// 预约单拒绝
				reOrderView.setStatus("-1");
				endedList.add(reOrderView);
			} else if ("1".equals(obj[7].toString())) {// 预约单已接受
				if ("2".equals(obj[6].toString())) {
					reOrderView.setStatus("2");
					endedList.add(reOrderView);
				} else {
					reOrderView.setStatus("1");
					orderList.add(reOrderView);
				}
			}
		}
		for (Object[] obj : caterSaleOrderList) {
			CateringReOrderView reOrderView = new CateringReOrderView();
			reOrderView.setOrderId(obj[8].toString());
			reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj[0].toString()));
			reOrderView.setStatus(obj[1].toString());
			reOrderView.setPayStatus(obj[2].toString());
			reOrderView.setCreateTime(obj[3].toString());
			reOrderView.setTable(objToString(obj[4]));
			reOrderView.setName(objToString(obj[5]));
			reOrderView.setPhone(objToString(obj[6]));
			reOrderView.setAddress(objToString(obj[7]));
			reOrderView.setType("2");
			reOrderView.setCarterType("2");
			if(obj[4] != null) {
				reOrderView.setCarterType("1");
			}
			if ("0".equals(obj[1].toString())) {
				reOrderView.setStatus("1");
				orderList.add(reOrderView);
			} else  {
				endedList.add(reOrderView);
			}
		}

		Collections.sort(orderList, new Comparator<CateringReOrderView>() {
			public int compare(CateringReOrderView a, CateringReOrderView b) {
				return b.getCreateTime().compareTo(a.getCreateTime());
			}
		});
		
		Collections.sort(endedList, new Comparator<CateringReOrderView>() {
			public int compare(CateringReOrderView a, CateringReOrderView b) {
				return b.getCreateTime().compareTo(a.getCreateTime());
			}
		});
		
		return new ModelAndView("yuding/cymyorder")
				.addObject("orderList", orderList)
				.addObject("endedList", endedList)
				.addObject("mid", mid)
				.addObject("openId", openId);
	}*/

	/**
	 * 进入餐点订单列表
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/myorders", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView myOrder(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid) {
		
		CateringSaleOrderListQueryInput saleOrderListQueryInput = new CateringSaleOrderListQueryInput();
		saleOrderListQueryInput.setOpenId(openId);
		saleOrderListQueryInput.setMid(mid);
		//input.setPageNo(pageNo);
		CateringSaleOrderListQueryOutput saleOrderListQueryOutput = (CateringSaleOrderListQueryOutput) wizarposOpenRestClient.post(saleOrderListQueryInput, "/catering/saleorder/list/query", CateringSaleOrderListQueryOutput.class);							
		List<CateringSaleOrderDto> caterSaleOrderList = saleOrderListQueryOutput.getSaleOrderList();		

		List<CateringReOrderView> orderList = new ArrayList<CateringReOrderView>();
		List<CateringReOrderView> endedList = new ArrayList<CateringReOrderView>();

		for (CateringSaleOrderDto obj : caterSaleOrderList) {
			CateringReOrderView reOrderView = new CateringReOrderView();
			try {
				BeanUtils.copyProperties(reOrderView, obj);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}			
			reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj.getShowOrderId()));			
			reOrderView.setType("2");
			if ("0".equals(obj.getStatus())) {
				reOrderView.setStatus("1");
				orderList.add(reOrderView);				
			} else  {
				endedList.add(reOrderView);
			}
		}
		
		Collections.sort(orderList, new Comparator<CateringReOrderView>() {
			public int compare(CateringReOrderView a, CateringReOrderView b) {
				return b.getCreateTime().compareTo(a.getCreateTime());
			}
		});
		
		Collections.sort(endedList, new Comparator<CateringReOrderView>() {
			public int compare(CateringReOrderView a, CateringReOrderView b) {
				return b.getCreateTime().compareTo(a.getCreateTime());
			}
		});
		
		return new ModelAndView("yuding/cymyorder")
				.addObject("orderList", orderList)
				.addObject("endedList", endedList)
				.addObject("mid", mid)
				.addObject("openId", openId);
	}	
	
	/**
	 * 进入餐点预订单列表
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/myreorders", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView myReOrder(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid) {

		CateringReOrderListQueryInput reOrderListQueryInput = new CateringReOrderListQueryInput();
		reOrderListQueryInput.setOpenId(openId);
		reOrderListQueryInput.setMid(mid);
		//input.setPageNo(pageNo);
		CateringReOrderListQueryOutput reOrderListQueryOutput = (CateringReOrderListQueryOutput) wizarposOpenRestClient.post(reOrderListQueryInput, "/catering/reorder/list/query", CateringReOrderListQueryOutput.class);									
		List<CateringReOrderDto> caterOrderList = reOrderListQueryOutput.getOrderList();

		List<CateringReOrderView> orderList = new ArrayList<CateringReOrderView>();
		List<CateringReOrderView> endedList = new ArrayList<CateringReOrderView>();
		
		for (CateringReOrderDto obj : caterOrderList) {			
			CateringReOrderView reOrderView = new CateringReOrderView();		
			try {
				BeanUtils.copyProperties(reOrderView, obj);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}			
			reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj.getShowOrderId()));
			reOrderView.setType("1");
			if (obj.getAuditFlag() ==  null || "0".equals(obj.getAuditFlag().toString())) {// 待接受
				reOrderView.setStatus("0");
				orderList.add(reOrderView);				
			} else if ("2".equals(obj.getAuditFlag().toString())) {// 预约单拒绝
				reOrderView.setStatus("-1");
				endedList.add(reOrderView);
			} else if ("1".equals(obj.getAuditFlag().toString())) {// 预约单已接受
				if ("2".equals(obj.getStatus().toString())) {
					reOrderView.setStatus("2");
					endedList.add(reOrderView);
				} else {
					reOrderView.setStatus("1");
					orderList.add(reOrderView);
				}
			}
		}
		
		Collections.sort(orderList, new Comparator<CateringReOrderView>() {
			public int compare(CateringReOrderView a, CateringReOrderView b) {
				return b.getCreateTime().compareTo(a.getCreateTime());
			}
		});
		
		Collections.sort(endedList, new Comparator<CateringReOrderView>() {
			public int compare(CateringReOrderView a, CateringReOrderView b) {
				return b.getCreateTime().compareTo(a.getCreateTime());
			}
		});
		
		return new ModelAndView("yuding/cymyorder")
				.addObject("orderList", orderList)
				.addObject("endedList", endedList)
				.addObject("mid", mid)
				.addObject("openId", openId);
	}	
	
	private String objToString(Object obj) {
		if(obj != null) {
			return obj.toString();
		}else{
			return "";
		}
	}

/*	private String getPrituce(String productId) {
		ErpProduct erpP = erpProductService.getErpProductById(productId);
		if (erpP != null && null != erpP.getPicId()
				&& !erpP.getPicId().equals("")) {
			String picIds[] = erpP.getPicId().split(",");
			if (picIds.length > 0) {
				// 注意id为空的情况
				if (erpProductPicDefService.getErpProductPicDefById(picIds[0]) != null)
					return Function.dealGridPicUrl(erpProductPicDefService
							.getErpProductPicDefById(picIds[0]).getAddress(),
							150, 150);
			}
		} else {
			return SysConstants.DEFAULT_PICTURE;
		}
		return "";
	}

	@SuppressWarnings("unused")
	private void getproductsUnderCategory(String mid, String parentId,
			List<ErpProduct> productList) {
		List<ErpProductCategory> categoryList = erpProductCategoryService
				.getErpProductCategoryByParentId(mid, parentId);
		if (categoryList == null || categoryList.size() == 0) {
			return;
		}
		for (ErpProductCategory category : categoryList) {
			String categoryId = category.getId();
			List<ErpProduct> list = erpProductService.getErpProductListByMid(
					mid, categoryId);
			// 处理价格分-元，图片路径
			for (ErpProduct ep : list) {
				ep.setPrice(Utils.formatAmount(ep.getPrice()));
				ep.setPicUrl(getPrituce(ep.getId()));
			}
			productList.addAll(list);
			getproductsUnderCategory(mid, categoryId, productList);
		}
	}*/

/*	*//**
	 * 进入呼叫
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping(value = "/tohujiao", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toHujiao(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception {

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("openId", openId);
		data.put("mid", mid);
		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/tohujiao");
		tmpUrl.append("?mid=").append(mid);
		tmpUrl.append("&openId=").append(openId);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		String apiTicket = wxAuthentication.getJsTicket(mid);
		// 微信 js config 签名
		Map<String, String> ret = WxSignUtil.commonSign(apiTicket, url,
				WxSignUtil.createTimestamp());
		data.putAll(ret);
		data.put("appId", merchantDefService.getSysMerchantDefByMid(mid)
				.getAppid());
		return new ModelAndView("yuding/hujiao", data);
	}*/

	/**
	 * 进入呼叫
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tohujiao", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toHujiao(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception {

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("openId", openId);
		data.put("mid", mid);
		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/tohujiao");
		tmpUrl.append("?mid=").append(mid);
		tmpUrl.append("&openId=").append(openId);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}

		return new ModelAndView("yuding/hujiao", data);
	}
	
	/**
	 * 查看餐桌是否可用
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/usable", method = RequestMethod.GET)
	@ResponseBody
	public boolean usable(
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid) throws Exception {
		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("tableId", tableId);

		JSONObject respJson = null;
		try {
			respJson = wPosHttpClient.postOpen("/catering/table/using",
					json);
		} catch (Exception e) {
			// 消息推送失败
			log.error("餐桌状态查询失败，tableId：" + tableId);
			return false;
		}

		String code = respJson.getString("code");
		if ("0".equals(code)) {
			boolean using = respJson.getJSONObject("result").getBoolean("using");
			return !using;
		} else if ("60009".equals(code)|| "60028".equals(code)) {
			return false;
		}
		
		return true;
	}
	

/*	*//**
	 * 查看预订单是否可用
	 * AuditFlag=1 预约已经接受
	 * Status=0 尚未开台
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping(value = "/checkYuding", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkYuding(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid) throws Exception {
		ErpCarterOrder erpCarterOrder = erpCarterOrderService.getByIdMid(
				orderId, mid);
		if(erpCarterOrder != null && erpCarterOrder.getAuditFlag()==1 && "0".equals(erpCarterOrder.getStatus())) {
			return true;
		}
		return false;
	}*/
	
	/**
	 * 查看预订单是否可用
	 * AuditFlag=1 预约已经接受
	 * Status=0 尚未开台
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkYuding", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkYuding(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid) throws Exception {
		CateringOrderQueryInput input = new CateringOrderQueryInput();
		input.setMid(mid);
		input.setReOrderId(orderId);
		CateringOrderQueryOutput ouptut = (CateringOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/reorder/query", CateringOrderQueryOutput.class);		
				
		List<TableOrder> tableOrderList = ouptut.getResult();		
		if (tableOrderList.size() != 0 && "1".equals(tableOrderList.get(0).getAuditFlag()) 
				&& "0".equals(tableOrderList.get(0).getStatus())) {		
			return true;
		}
		return false;
	}		
}
